package com.badu.common.exception;

import com.badu.common.config.Constant;
import com.badu.common.domain.LogDO;
import com.badu.common.enums.ServerErrorEnum;
import com.badu.common.service.LogService;
import com.badu.common.utils.HttpServletUtils;
import com.badu.common.utils.R;
import com.badu.common.utils.ShiroUtils;
import com.badu.system.domain.UserDO;

import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

import java.sql.SQLSyntaxErrorException;
import java.util.Date;
import java.util.List;

/**
 * 异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	LogService logService;
//
//    /**
//     * 自定义异常
//     */
    @ExceptionHandler(RuntimeException.class)
    public R handleBDException(RuntimeException e) {
        logger.error("服务器内部错误 {}",e.getMessage());
        R r = new R();
        r.put("code", ServerErrorEnum.SERVER_ERROR.getCode());
        r.put("msg", e.getMessage());
        return r;
    }
//
//    @ExceptionHandler(DuplicateKeyException.class)
//    public R handleDuplicateKeyException(DuplicateKeyException e) {
//        logger.error(e.getMessage(), e);
//        return R.error("数据库中已存在该记录");
//    }
//
//    @ExceptionHandler(org.springframework.web.servlet.NoHandlerFoundException.class)
//    public R noHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException e) {
//        logger.error(e.getMessage(), e);
//        return R.error(404, "没找找到页面");
//    }

	@ExceptionHandler(AuthorizationException.class)
	public Object handleAuthorizationException(AuthorizationException e, HttpServletRequest request) {
		logger.error(e.getMessage(), e);
		if (HttpServletUtils.jsAjax(request)) {
			return R.error(ServerErrorEnum.NO_AUTH.getCode(), "未授权");
		}
		return new ModelAndView("error/403");
	}

	@ExceptionHandler({ Exception.class })
	public Object handleException(Exception e, HttpServletRequest request) {
		LogDO logDO = new LogDO();
		logDO.setGmtCreate(new Date());
		logDO.setOperation(Constant.LOG_ERROR);
		logDO.setMethod(request.getRequestURL().toString());
		logDO.setParams(e.toString());
		UserDO current = ShiroUtils.getUser();
		if (null != current) {
			logDO.setUserId(current.getUserId());
			logDO.setUsername(current.getUsername());
		}
		logService.save(logDO);
		logger.error(e.getMessage(), e);
		if (HttpServletUtils.jsAjax(request)) {
			return R.error(ServerErrorEnum.SERVER_ERROR.getCode(), "服务器错误，请联系管理员");
		}
		return new ModelAndView("error/500");
	}

	@ExceptionHandler({ LoginException.class })
	public Object handleLoginException(LoginException e, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		log.error("  获取用户信息失败，准备让用户重新登录   失败原因:{} ", e.getMessage());
		mav.addObject("msg", e.getMessage());
		mav.setViewName("login");
		return mav;
	}

	@org.springframework.web.bind.annotation.ExceptionHandler(BindException.class)
	public R handleBindException(HttpServletRequest request, BindException exception) {
		List<FieldError> allErrors = exception.getFieldErrors();
		StringBuilder sb = new StringBuilder();
		for (FieldError errorMessage : allErrors) {
			sb.append(errorMessage.getField()).append(": ").append(errorMessage.getDefaultMessage()).append(", ");
		}
		log.error(" 参数验证失败 {} ",sb.toString());
		return R.error(ServerErrorEnum.LACK_PARAM.getCode(),sb.toString());
	}

	@org.springframework.web.bind.annotation.ExceptionHandler(ConstraintViolationException.class)
	public R handleBindException2(HttpServletRequest request, ConstraintViolationException exception) {
		String message = exception.getMessage();
		if (message.contains(".")) {
			String[] split = message.split("\\.");
			message = split[1];
		}
		log.error(" 参数验证失败 {} ",message);
		return R.error(ServerErrorEnum.LACK_PARAM.getCode(),message);
	}

	@org.springframework.web.bind.annotation.ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public R handleBindException2(HttpServletRequest request, HttpRequestMethodNotSupportedException exception) {
		log.error(" 请求方式失败 {} ",exception.getMessage());
		return R.error(ServerErrorEnum.REQUEST_ERROR.getCode(),exception.getMessage());
	}
	
	@ExceptionHandler(BDException.class)
	public R handleSqlException( BDException exception) {
		log.error(" sql异常 {} ",exception.getMessage());
		return R.error(ServerErrorEnum.SQL_ERROR.getCode(),exception.getMessage());
	}
	
	@ExceptionHandler(IllegalArgumentException.class)
	public R handleIllegalArgumentException( IllegalArgumentException exception) {
		log.error(" 程序手动抛出异常 {} ",exception.getMessage());
		return R.error(ServerErrorEnum.SERVER_ERROR.getCode(),exception.getMessage());
	}
}
